/**
 * 留言管理页面
 */
import React, { useState } from 'react';
import { toast } from 'sonner';
import AdminLayout from '@/components/admin/AdminLayout';
import { 
  useMessages, 
  useMessageStats, 
  useUpdateMessage, 
  useDeleteMessage,
  useMarkMessageRead,
  useMarkAllMessagesRead
} from '@/hooks/useMessages';
import { Message, MessageUpdate } from '@/types';

export default function MessageManagement() {
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(10);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [filterRead, setFilterRead] = useState<boolean | undefined>(undefined);
  const [filterReplied, setFilterReplied] = useState<boolean | undefined>(undefined);
  const [selectedMessage, setSelectedMessage] = useState<Message | null>(null);
  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [isReplyModalOpen, setIsReplyModalOpen] = useState(false);
  const [replyContent, setReplyContent] = useState('');

  // API hooks
  const { data: messagesData, isLoading } = useMessages({
    page: currentPage,
    size: pageSize,
    keyword: searchKeyword || undefined,
    is_read: filterRead,
    is_replied: filterReplied,
  });

  const { data: stats } = useMessageStats();
  const updateMessage = useUpdateMessage();
  const deleteMessage = useDeleteMessage();
  const markMessageRead = useMarkMessageRead();
  const markAllMessagesRead = useMarkAllMessagesRead();

  // 处理搜索
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setCurrentPage(1);
  };

  // 查看留言详情
  const viewMessage = (message: Message) => {
    setSelectedMessage(message);
    setIsViewModalOpen(true);
    
    // 如果未读，标记为已读
    if (!message.is_read) {
      markMessageRead.mutate(message.id);
    }
  };

  // 回复留言
  const replyMessage = (message: Message) => {
    setSelectedMessage(message);
    setReplyContent(message.reply_content || '');
    setIsReplyModalOpen(true);
  };

  // 提交回复
  const submitReply = async () => {
    if (!selectedMessage || !replyContent.trim()) {
      toast.error('请输入回复内容');
      return;
    }

    try {
      await updateMessage.mutateAsync({
        id: selectedMessage.id,
        data: {
          reply_content: replyContent.trim(),
          is_replied: true,
        }
      });
      
      toast.success('回复成功');
      setIsReplyModalOpen(false);
      setReplyContent('');
      setSelectedMessage(null);
    } catch (error) {
      console.error('回复失败:', error);
      toast.error('回复失败，请重试');
    }
  };

  // 删除留言
  const handleDeleteMessage = async (id: number) => {
    if (!confirm('确定要删除这条留言吗？')) {
      return;
    }

    try {
      await deleteMessage.mutateAsync(id);
      toast.success('留言删除成功');
    } catch (error) {
      console.error('删除失败:', error);
      toast.error('删除失败，请重试');
    }
  };

  // 标记所有为已读
  const handleMarkAllRead = async () => {
    try {
      await markAllMessagesRead.mutateAsync();
      toast.success('已标记所有留言为已读');
    } catch (error) {
      console.error('操作失败:', error);
      toast.error('操作失败，请重试');
    }
  };

  // 格式化时间
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN');
  };

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* 页面头部 */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-800">留言管理</h1>
            <p className="text-gray-600">
              管理用户留言和咨询
              {stats && (
                <span className="ml-4 text-sm">
                  <span className="text-blue-600">总计: {stats.total}</span>
                  <span className="ml-3 text-orange-600">未读: {stats.unread}</span>
                  <span className="ml-3 text-red-600">未回复: {stats.unreplied}</span>
                  <span className="ml-3 text-green-600">今日: {stats.today}</span>
                </span>
              )}
            </p>
          </div>
          {stats && stats.unread > 0 && (
            <button
              type="button"
              onClick={handleMarkAllRead}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
              disabled={markAllMessagesRead.isPending}
            >
              <i className="fa-solid fa-check-double text-sm"></i>
              <span>全部标记已读</span>
            </button>
          )}
        </div>

        {/* 搜索和筛选 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <form onSubmit={handleSearch} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">搜索关键词</label>
                <input
                  type="text"
                  value={searchKeyword}
                  onChange={(e) => setSearchKeyword(e.target.value)}
                  placeholder="搜索姓名、电话、邮箱、主题或内容"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">阅读状态</label>
                <select
                  value={filterRead === undefined ? '' : filterRead.toString()}
                  onChange={(e) => setFilterRead(e.target.value === '' ? undefined : e.target.value === 'true')}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="">全部</option>
                  <option value="false">未读</option>
                  <option value="true">已读</option>
                </select>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">回复状态</label>
                <select
                  value={filterReplied === undefined ? '' : filterReplied.toString()}
                  onChange={(e) => setFilterReplied(e.target.value === '' ? undefined : e.target.value === 'true')}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="">全部</option>
                  <option value="false">未回复</option>
                  <option value="true">已回复</option>
                </select>
              </div>
              
              <div className="flex items-end">
                <button
                  type="submit"
                  className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  搜索
                </button>
              </div>
            </div>
          </form>
        </div>

        {/* 留言列表 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200">
          {isLoading ? (
            <div className="flex justify-center items-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
              <span className="ml-3 text-gray-600">加载留言...</span>
            </div>
          ) : messagesData?.items.length === 0 ? (
            <div className="text-center py-12">
              <i className="fa-solid fa-inbox text-4xl text-gray-300 mb-4"></i>
              <p className="text-gray-500">暂无留言</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50 border-b border-gray-200">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      联系人
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      主题
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      状态
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      提交时间
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {messagesData?.items.map((message) => (
                    <tr key={message.id} className={!message.is_read ? 'bg-blue-50' : ''}>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div>
                          <div className="text-sm font-medium text-gray-900 flex items-center">
                            {message.name}
                            {!message.is_read && (
                              <span className="ml-2 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                新
                              </span>
                            )}
                          </div>
                          <div className="text-sm text-gray-500">{message.phone}</div>
                          {message.email && (
                            <div className="text-sm text-gray-500">{message.email}</div>
                          )}
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="text-sm text-gray-900">
                          {message.subject || '无主题'}
                        </div>
                        <div className="text-sm text-gray-500 truncate max-w-xs">
                          {message.message}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="space-y-1">
                          <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                            message.is_read 
                              ? 'bg-green-100 text-green-800' 
                              : 'bg-gray-100 text-gray-800'
                          }`}>
                            {message.is_read ? '已读' : '未读'}
                          </span>
                          <br />
                          <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                            message.is_replied 
                              ? 'bg-blue-100 text-blue-800' 
                              : 'bg-orange-100 text-orange-800'
                          }`}>
                            {message.is_replied ? '已回复' : '未回复'}
                          </span>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {formatDate(message.created_at)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                        <button
                          type="button"
                          onClick={() => viewMessage(message)}
                          className="text-blue-600 hover:text-blue-900"
                        >
                          查看
                        </button>
                        <button
                          type="button"
                          onClick={() => replyMessage(message)}
                          className="text-green-600 hover:text-green-900"
                        >
                          回复
                        </button>
                        <button
                          type="button"
                          onClick={() => handleDeleteMessage(message.id)}
                          className="text-red-600 hover:text-red-900"
                        >
                          删除
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* 分页 */}
        {messagesData && messagesData.pages > 1 && (
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 px-6 py-4">
            <div className="flex items-center justify-between">
              <div className="text-sm text-gray-700">
                显示第 {((currentPage - 1) * pageSize) + 1} 到 {Math.min(currentPage * pageSize, messagesData.total)} 条，
                共 {messagesData.total} 条留言
              </div>
              <div className="flex space-x-2">
                <button
                  type="button"
                  onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                  disabled={currentPage === 1}
                  className="px-3 py-1 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  上一页
                </button>

                {Array.from({ length: messagesData.pages }, (_, i) => i + 1)
                  .filter(page =>
                    page === 1 ||
                    page === messagesData.pages ||
                    Math.abs(page - currentPage) <= 2
                  )
                  .map((page, index, array) => (
                    <React.Fragment key={page}>
                      {index > 0 && array[index - 1] !== page - 1 && (
                        <span className="px-3 py-1 text-sm text-gray-500">...</span>
                      )}
                      <button
                        type="button"
                        onClick={() => setCurrentPage(page)}
                        className={`px-3 py-1 text-sm border rounded-md ${
                          currentPage === page
                            ? 'bg-blue-600 text-white border-blue-600'
                            : 'border-gray-300 hover:bg-gray-50'
                        }`}
                      >
                        {page}
                      </button>
                    </React.Fragment>
                  ))}

                <button
                  type="button"
                  onClick={() => setCurrentPage(Math.min(messagesData.pages, currentPage + 1))}
                  disabled={currentPage === messagesData.pages}
                  className="px-3 py-1 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  下一页
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 查看留言模态框 */}
      {isViewModalOpen && selectedMessage && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold text-gray-800">留言详情</h2>
                <button
                  type="button"
                  onClick={() => setIsViewModalOpen(false)}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <i className="fa-solid fa-times text-xl"></i>
                </button>
              </div>

              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                    <p className="text-gray-900">{selectedMessage.name}</p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">电话</label>
                    <p className="text-gray-900">{selectedMessage.phone}</p>
                  </div>
                </div>

                {selectedMessage.email && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                    <p className="text-gray-900">{selectedMessage.email}</p>
                  </div>
                )}

                {selectedMessage.subject && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">主题</label>
                    <p className="text-gray-900">{selectedMessage.subject}</p>
                  </div>
                )}

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">留言内容</label>
                  <div className="bg-gray-50 p-4 rounded-lg">
                    <p className="text-gray-900 whitespace-pre-wrap">{selectedMessage.message}</p>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">提交时间</label>
                    <p className="text-gray-900">{formatDate(selectedMessage.created_at)}</p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">状态</label>
                    <div className="space-x-2">
                      <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                        selectedMessage.is_read
                          ? 'bg-green-100 text-green-800'
                          : 'bg-gray-100 text-gray-800'
                      }`}>
                        {selectedMessage.is_read ? '已读' : '未读'}
                      </span>
                      <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                        selectedMessage.is_replied
                          ? 'bg-blue-100 text-blue-800'
                          : 'bg-orange-100 text-orange-800'
                      }`}>
                        {selectedMessage.is_replied ? '已回复' : '未回复'}
                      </span>
                    </div>
                  </div>
                </div>

                {selectedMessage.is_replied && selectedMessage.reply_content && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">回复内容</label>
                    <div className="bg-blue-50 p-4 rounded-lg">
                      <p className="text-gray-900 whitespace-pre-wrap">{selectedMessage.reply_content}</p>
                      {selectedMessage.reply_time && (
                        <p className="text-sm text-gray-500 mt-2">
                          回复时间: {formatDate(selectedMessage.reply_time)}
                        </p>
                      )}
                    </div>
                  </div>
                )}
              </div>

              <div className="flex justify-end space-x-4 mt-6 pt-6 border-t">
                <button
                  type="button"
                  onClick={() => setIsViewModalOpen(false)}
                  className="px-6 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  关闭
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setIsViewModalOpen(false);
                    replyMessage(selectedMessage);
                  }}
                  className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  回复留言
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 回复留言模态框 */}
      {isReplyModalOpen && selectedMessage && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold text-gray-800">回复留言</h2>
                <button
                  type="button"
                  onClick={() => {
                    setIsReplyModalOpen(false);
                    setReplyContent('');
                  }}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <i className="fa-solid fa-times text-xl"></i>
                </button>
              </div>

              <div className="space-y-4">
                <div className="bg-gray-50 p-4 rounded-lg">
                  <h3 className="font-medium text-gray-900 mb-2">原留言</h3>
                  <p className="text-sm text-gray-600 mb-2">
                    {selectedMessage.name} · {selectedMessage.phone}
                    {selectedMessage.subject && ` · ${selectedMessage.subject}`}
                  </p>
                  <p className="text-gray-900 whitespace-pre-wrap">{selectedMessage.message}</p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    回复内容 <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    value={replyContent}
                    onChange={(e) => setReplyContent(e.target.value)}
                    rows={6}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入回复内容..."
                  />
                </div>
              </div>

              <div className="flex justify-end space-x-4 mt-6 pt-6 border-t">
                <button
                  type="button"
                  onClick={() => {
                    setIsReplyModalOpen(false);
                    setReplyContent('');
                  }}
                  className="px-6 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  取消
                </button>
                <button
                  type="button"
                  onClick={submitReply}
                  disabled={updateMessage.isPending || !replyContent.trim()}
                  className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {updateMessage.isPending ? '提交中...' : '提交回复'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </AdminLayout>
  );
}
